import React, { useEffect, useRef, useState } from "react";
import { Modal,Alert,Divider,Tabs,Spin,Button, message,Empty} from 'antd';
import {LeftCircleOutlined,RightCircleOutlined} from '@ant-design/icons'
import {queryByBookId,QuerySentencesAndWordsByBookContentID,Revisesentencesandwords} from 'api/index'
import NestedTable from "pages/account/NestedTable";
const { TabPane } = Tabs;


const EditJsonBook = (props) => {
  const {isModalVisible, setIsModalVisible,id} = props

  const [time,setTime] = useState(0)
  const [bookInfo,setBookInfo] = useState({})
  const [content,setContent] = useState([])
  const [contentIndex,setContentIndex] = useState(1)
  const [img,setImg] = useState('')
  const [imgInfo,setimgInfo] = useState({})
  const [audioUrl,setAudio] = useState('')
  const [loading,setLoading] = useState(false)
  const [spinning,setSpinning] = useState(false)
  const audio = useRef(null)
  const imgRef = useRef(null)

  useEffect(()=>{
    isModalVisible&&getJsonData()
  },[isModalVisible])// eslint-disable-line react-hooks/exhaustive-deps
  
  useEffect(()=>{
    if(!bookInfo.id) return
    setAudio('')
    setTime(0)
    setImg(bookInfo.contentFlows[contentIndex - 1].pictureUrl)

    getJonText()
  },[contentIndex])// eslint-disable-line react-hooks/exhaustive-deps
  
  // 获取最新数据
  const getJsonData = async() => {

    if(!id) return
    
       if(!bookInfo.id){
         setSpinning(true)
         const res = await queryByBookId(id)
         setBookInfo(res.result)

         if(res.result.contentFlows&&res.result.contentFlows.length){
           

         setImg(res.result.contentFlows[0].pictureUrl)


          setLoading(true)

          
          if(imgRef.current){
            setimgInfo({
              xWidth:imgRef.current.naturalWidth,
              yHeight:imgRef.current.naturalHeight,
             })

          const res1 = await QuerySentencesAndWordsByBookContentID(res.result.contentFlows[0].id)
          
          setContent(res1.result)

          setLoading(false)


          if(!res.result.contentFlows[0].audioUrl)  return  setSpinning(false)

           setAudio(res.result.contentFlows[0].audioUrl)

            audio.current.load()

            setTimeout(()=>{
              audio.current.play()

               setSpinning(false)

            },1000)


          }
        }
       }
  }
  // 获取当前字幕
  const getJonText = async() => {
    setLoading(true)

    const res = await QuerySentencesAndWordsByBookContentID(bookInfo.contentFlows[contentIndex-1].id)

    setContent(res.result)


    if(!bookInfo.contentFlows[contentIndex-1].audioUrl) {

     if(bookInfo.contentFlows[contentIndex-1].captionUrl){
      //  存在字幕
      setAudio(bookInfo.contentFlows[contentIndex-2].audioUrl)

      audio.current.load()
  
       setTimeout(()=>{
        audio.current.play()
  
        setLoading(false)
  
      },300)
     }

      setLoading(false)
      return
    }  

    setAudio(bookInfo.contentFlows[contentIndex-1].audioUrl)

    audio.current.load()

     setTimeout(()=>{
      audio.current.play()

      setLoading(false)

    },300)

  }
  // 返回
  const handleOk = async () => {
    const data = {
      contentId:content[0].flowBookContentId||content[0].bookContentId,
      sentences:content.map((i,j)=>{
        return {
          bg: i.wordFlows?i.wordFlows[0].wordBg:'',
          bookContentId: i.bookContentId,
          ed: i.wordFlows?i.wordFlows[i.wordFlows.length-1].wordEd:'',
          onebest:i.onebest,
          sort: j,
          wordFlows:i.wordFlows
        }
      })
    }
    // 请求修改
    await Revisesentencesandwords(data)
    message.success('修改成功')

    getJonText()
  }
  // 确认修改
  const onCancel = () => {
    setIsModalVisible(false);
  };
  // 播放中
  const onTimeUpdate = (e) => {
    setTime(e.target.currentTime*1000)
  }
  // 播放结束
  const onEnded = ()=> {
    setTime(0)
  }
  // 上一张
  const nextPage = () => {
    setContent([])
    if(contentIndex===1) {
      setContentIndex(bookInfo.contentFlows.length)
      return //已经是第一张 返回最后一张
    }
    setContentIndex(i=>i-1)
  }
  // 下一张
  const prevPage = () => {
    setContent([])
    if(contentIndex===bookInfo.contentFlows.length) {
      setContentIndex(1)
      return //已经是最后一张 返回第一张
    }
    setContentIndex(i=>i+1)
  }
  
  return   <Modal destroyOnClose wrapClassName="modal-full"   visible={isModalVisible} onOk={handleOk} onCancel={onCancel}>
      <div className="full-modal-title">
          <Alert message={'字幕预览 / 编辑'} type="success" />
      </div>

      <Button onClick={handleOk} disabled={spinning||!id} type={'primary'} size={'small'} className='json-btn'>确认编辑此页字幕</Button>

      <Spin tip="Loading..." spinning={spinning}>
      <div className="edit-json">

        <div className="json-img">
             <img ref={imgRef} src={img} alt="" />
             {/* 字幕 */}
             <div className="onebest">
               {/* time */}
               {
                content?content.map(i=>{
                   return <span key={i.id}>
                   {
                     time>i.bg&&time<i.ed?i.onebest:''
                   }
                   </span>
                 }):''
               }

             </div>

             {/* 单词 */}
             <div className="word-json">
               {
                 content&&content.map(i=>i.wordFlows)?content.map(i=>i.wordFlows).flat().map(x=>{
                   return x.width?<div key={x.id}  style={{fontWeight: 900,width:(x.width-x.x) * 0.01 * 600 + 'px',lineHeight:(x.height-x.y) * 0.01 * imgInfo.yHeight + 'px',height:(x.height-x.y) * 0.01 * imgInfo.yHeight + 'px',fontSize:(x.height-x.y) * 0.01 * imgInfo.yHeight / 2 - 2+ 'px',position:'absolute',left: x.x *  5 + 'px',top:600 / imgInfo.xWidth * imgInfo.yHeight - 600 / imgInfo.xWidth * imgInfo.yHeight * x.y * 0.01 - (x.height-x.y) * 0.01 * imgInfo.yHeight + 86 + 'px',zIndex:999}}>
                     {time>x.wordBg&&time<x.wordEd?x.wordsName:''}
                   </div>
                   :<div key={x.id} style={{fontWeight: 900,position:'absolute',left:'250px',fontSize:'20px',top: imgInfo.yHeight - 10 + 'px'}} >
                    {time>x.wordBg&&time<x.wordEd?x.wordsName:''}
                  </div>
                 }):''
               }
             </div>
            
             {
               id?<>
                {/* 上一张 */}
             <LeftCircleOutlined onClick={nextPage} className="icon1"/>
             {/* 下一张 */}
             <RightCircleOutlined onClick={prevPage} className="icon2" />
               </>:''
             }
            
        </div>


       {/* 此绘本无数据 */}
        
       {
         bookInfo.contentFlows&&bookInfo.contentFlows.length? <div className="json-text">

         <Divider plain>字幕文件编辑</Divider>
         {/* 音频 */}
         <audio src={audioUrl} onEnded={onEnded} ref={audio} onTimeUpdate={onTimeUpdate} controls style={{width:'100%',height:'38px'}}></audio>
         
         {/* 句子 */}

         {/* 单词 */}

         {/* 时间 */}

         <NestedTable setContent={setContent} time={time}  content={content} loading={loading}></NestedTable>



       </div>:<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
       }
       
      </div>
     </Spin>
   
     
   </Modal>

}
export default EditJsonBook